//
//  RBInvoiceNowVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/8/3.
//

#import "RBInvoiceNowVC.h"
#import "UIView+RBAdd.h"
#import "UIScrollView+RBAdd.h"
#import <Masonry.h>
#import "RBThemeConfig.h"
#import <UIColor+YYAdd.h>
#import <UIView+YYAdd.h>
#import "RBPager.h"
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "RanTool.h"
#import "UIViewController+RBAdd.h"
#import "RBInvoiceNowResponse.h"
#import "RBNavigationBar.h"
#import "RBInvoiceNowCell.h"
#import "RBInvoiceHeaderManageVC.h"

@interface RBInvoiceNowVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, strong)UILabel *bottomL;
@property(nonatomic, strong)UIImageView *bottomSelectImgView;
@property(nonatomic, assign)BOOL selectAll;
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong)NSMutableArray *dataSource;

@property (nonatomic, strong) RBInvoiceNowResponse *response;

@end

@implementation RBInvoiceNowVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
    [self.listView.mj_header beginRefreshing];
}

#pragma mark - Private

- (void)setup
{
    self.title = @"我要开票";
    [self fillData];
}

- (void)fillData
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObject:({
        RBGroupModel *group = RBGroupModel.new;
        group.sectionInset = UIEdgeInsetsMake(Zoom(10), 0, Zoom(10), 0);
        group.minimumLineSpacing = Zoom(10);
        group.cellModels = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
        group;
    })];
    [self appendData];
}

- (void)appendData {
    __weak typeof(self) weakSelf = self;
    NSMutableArray *arrayM = ({
        RBGroupModel *group = weakSelf.dataSource.lastObject;
        (NSMutableArray *)group.cellModels;
    });
    for (RBInvoiceNowModel *model in self.response.data) {
        [arrayM addObject:({
            RBCellModel *cellModel = RBCellModel.new;
            cellModel.reuseCellIdentifier = NSStringFromClass(RBInvoiceNowCell.class);
            cellModel.itemSize = CGSizeMake(Zoom(350), Zoom(151));
            cellModel.cellData = model;
            cellModel.eventBlock = ^(RBInvoiceNowModel *data) {
                NSArray *models = [RanTool modelsWithSection:0 dataSource:weakSelf.dataSource];
                BOOL selectAll = YES;
                for (RBInvoiceNowModel *model in models) {
                    if (!model.selected) {
                        selectAll = NO;
                        break;
                    }
                }
                weakSelf.selectAll = selectAll;
                [weakSelf reloadDisplay];
                [weakSelf.collectionView reloadData];
            };
            cellModel;
        })];
    }
    [self reloadDisplay];
    [self.collectionView reloadData];
}

- (void)reloadDisplay
{
    NSArray *models = [RanTool modelsWithSection:0 dataSource:self.dataSource];
    NSInteger totalCount = 0;
    NSString *totalPrice = @"0";
    for (RBInvoiceNowModel *model in models)
    {
        if(model.selected)
        {
            totalCount++;
            totalPrice = [RanTool num:totalPrice plusNum:model.total_price];
        }
    }
    self.bottomL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
        UIFont *font = [UIFont systemFontOfSize:Zoom(13)];
        UIColor *blackColor = [RBThemeConfig textBlackColor];
        UIColor *redColor = [UIColor colorWithHexString:@"#F3665C"];
        [maker addAttributeStringWithFont:font color:blackColor string:@"已选"];
        [maker addAttributeStringWithFont:font color:redColor string:[NSString stringWithFormat:@"%zd", totalCount]];
        [maker addAttributeStringWithFont:font color:blackColor string:@"项"];
        [maker addAttributeStringWithFont:font color:redColor string:totalPrice];
        [maker addAttributeStringWithFont:font color:blackColor string:@"元"];
    }];
    
    self.bottomSelectImgView.image = self.selectAll? [self selImg]: [self norImg];
}
- (UIImage *)selImg
{
    return [UIImage imageNamed:@"addressListDefault"];
}

- (UIImage *)norImg
{
    return [UIImage imageNamed:@"unsel"];
}

#pragma mark - Network
- (NSString *)listPageKey
{
    return @"page";
}
- (NSDictionary *)listParams
{
    NSMutableDictionary *dicM = NSMutableDictionary.dictionary;
    dicM[@"user_id"] = [RBAccountManager getUserId];
    return dicM;
}
- (NSString *)listRequestPath
{
    return _Invoice_order_list;
}
- (NSInteger)ListCurrentPage
{
    return self.response.currentPage;
}
- (BOOL)listLog
{
    return YES;
}
- (BOOL)listPost
{
    return YES;
}
- (Class)listResponseClass
{
    return RBInvoiceNowResponse.class;
}
- (UIScrollView *)listView
{
    return self.collectionView;
}

- (void)getFirstPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadFirstPageWithDesView:self.listView showPlaceHolder:YES sucBlock:^(id data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(id data) {
        
    } reloadBlock:^{
        [weak_self getFirstPageData];
    }];
}
- (void)getNextPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadNextPageWithSucBlock:^(id data) {
        weak_self.response = data;
        [weak_self appendData];
    } failBlock:^(id data) {
        
    }];
}


#pragma mark - Event

- (void)selectAllBtnTapped
{
    self.selectAll = !self.selectAll;
    NSArray *models = [RanTool modelsWithSection:0 dataSource:self.dataSource];
    for (RBInvoiceNowModel *model in models)
    {
        model.selected = self.selectAll;
    }
    [self.collectionView reloadData];
    [self reloadDisplay];
}

- (void)confirmBtnTapped
{
    NSArray *models = [RanTool modelsWithSection:0 dataSource:self.dataSource];
    NSInteger totalCount = 0;
    NSMutableArray *orderIDArray = [NSMutableArray array];
    for (RBInvoiceNowModel *model in models) {
        if(model.selected) {
            totalCount++;
            [orderIDArray addObject:model.order_id];
        }
    }
    if (totalCount == 0) {
        [JKToast showWithText:@"请选择要开票的订单"];
    } else {
        RBInvoiceHeaderManageVC *vc = RBInvoiceHeaderManageVC.new;
        LCWeakSelf;
        vc.block = ^(RBInvoiceHeaderManageModel * _Nonnull model) {
            [weakSelf applyInvoiceDataWith:model order_id:[orderIDArray componentsJoinedByString:@","]];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)applyInvoiceDataWith:(RBInvoiceHeaderManageModel *)model order_id:(NSString *)order_id {
    LCWeakSelf;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"order_id"] = order_id;
        dicM[@"fapiao_company_id"] = model.id;
        dicM[@"user_id"] = [RBAccountManager getUserId];
    } path:_Invoice_submit post:YES log:YES responseClass:RBResponse.class desView:self.view showHud:NO showPlaceHolder:NO sucBlock:^(RBResponse *data) {
        [JKToast showWithText:@"申请成功"];
        [weakSelf.listView.mj_header beginRefreshing];
    } failBlock:^(RBResponse *data) {
        [weakSelf.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}


#pragma mark - UICollectionViewDataSource & UICollectionViewDelegate

kRBCollectionViewDataSourceAndDelegate(self.dataSource);

#pragma mark - Setter

#pragma mark - Getter

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        self.collectionView = ({
            UICollectionViewFlowLayout *layout = UICollectionViewFlowLayout.new;
            UICollectionView *view = [UICollectionView.alloc initWithFrame:CGRectZero collectionViewLayout:layout];
            view.showsVerticalScrollIndicator = NO;
            view.showsHorizontalScrollIndicator = NO;
            view.dataSource = self;
            view.delegate = self;
            view.backgroundColor = [RBThemeConfig bgGrayColor];
            view.mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getFirstPageData)];
            view.mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(getNextPageData)];
            kRBIgnoreScrollViewInsetsAdjust(view);
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(0);
                make.right.mas_equalTo(0);
                make.bottom.mas_equalTo(self.bottomView.mas_top);
                make.top.mas_equalTo(0);
            }];
            view;
        });
    }
    return _collectionView;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        self.dataSource = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
    }
    return _dataSource;
}

- (UIView *)bottomView
{
    if (!_bottomView)
    {
        self.bottomView = ({
            UIView *view = UIView.new;
            view.backgroundColor = UIColor.whiteColor;
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.height.mas_equalTo(kRBSafeBottomHeight + Zoom(120));
            }];
            
            UILabel *bottomL = UILabel.new;
            self.bottomL = bottomL;
            [view addSubview:bottomL];
            [bottomL mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(Zoom(22));
                make.top.mas_equalTo(0);
                make.height.mas_equalTo(Zoom(45));
            }];
            
            UIView *lineView = UIView.new;
            lineView.backgroundColor = [RBThemeConfig lineGrayColor];
            [view addSubview:lineView];
            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.top.mas_equalTo(bottomL.mas_bottom);
                make.height.mas_equalTo(1);
            }];
            
            UIImageView *selectImgView = UIImageView.new;
            [selectImgView rbAddTapGesWithTarget:self action:@selector(selectAllBtnTapped)];
            self.bottomSelectImgView = selectImgView;
            [selectImgView extendResponseArea];
            [view addSubview:selectImgView];
            [selectImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(bottomL);
                make.top.mas_equalTo(lineView.mas_bottom).offset(Zoom(29));
                make.width.height.mas_equalTo(Zoom(17));
            }];
            
            UILabel *selL = [RanTool labelWithFontSize:Zoom(16) weight:1 color:[RBThemeConfig textBlackColor] align:0 text:@"全选"];
            [selL rbAddTapGesWithTarget:self action:@selector(selectAllBtnTapped)];
            [view addSubview:selL];
            [selL mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(selectImgView);
                make.left.mas_equalTo(selectImgView.mas_right).offset(Zoom(7));
            }];
            
            UILabel *confrimL = [RanTool labelWithFontSize:Zoom(15) weight:1 color:UIColor.whiteColor align:1 text:@"开具发票"];
            [confrimL rbSetCornerRadius:Zoom(22)];
            [confrimL rbAddTapGesWithTarget:self action:@selector(confirmBtnTapped)];
            confrimL.backgroundColor = [UIColor colorWithHexString:@"#518CFF"];
            [view addSubview:confrimL];
            [confrimL mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(Zoom(128));
                make.height.mas_equalTo(Zoom(44));
                make.right.mas_equalTo(Zoom(-12));
                make.centerY.mas_equalTo(selectImgView);
            }];
            
            view;
        });
    }
    return _bottomView;
}

@end
